<?php

/**
 * 京东物流SDK
 */

namespace app\client\services;
use Lop\LopOpensdkPhp\Filters\ErrorResponseFilter;
use Lop\LopOpensdkPhp\Filters\IsvFilter;
use Lop\LopOpensdkPhp\Options;
use Lop\LopOpensdkPhp\Support\DefaultClient;
use Lop\LopOpensdkPhp\Support\GenericRequest;
const APP_KEY='4885695972f8443a9270497d92bef4fa';
const APP_SECRET='7a75e35f93ee489b889614e43bb119a4';
const CUSTOMER_CODE='021K2643448';
const PRODUCT_CODE='ed-m-0001';
const BASE_URI='https://api.jdl.com';
//const BASE_URI='https://uat-api.jdl.com';
const DOMAIN='ECAP';



class JDService
{

    /**
     * 获取accesstoken
     * @return string
     */
    protected static function getAccessToken(){
        // 	2024-06-07 09:21:36到期，到期后需重新授权
        //生产环境
        return '20e7dde4ec4f4b4cb81ae7a4dc86ea45';
        //预发环境
//        return '8e50b03f392d49a6a1278c7c98207914';
    }

    /**
     * JD request
     * @param $path 请求路由
     * @param $body 请求body
     * @return mixed
     * @throws \Lop\LopOpensdkPhp\SdkException
     */
    protected static function request($path,$body){
        $client = new DefaultClient(BASE_URI);
//      系统参数，应用的app_ley和app_secret，可从【控制台-应用管理-概览】中查看；access_token是用户授权时获取的令牌，用户授权相关说明请查看https://cloud.jdl.com/#/devSupport/53392
        $isvFilter = new IsvFilter(APP_KEY, APP_SECRET, self::getAccessToken());
        $errorResponseFilter = new ErrorResponseFilter();

        $request = new GenericRequest();
        $request->setDomain(DOMAIN);//对接方案的编码，应用订购对接方案后可在订阅记录查看
        $request->setPath($path);//api的path，可在API文档查看
        $request->setMethod("POST");//只支持POST
//      序列化后的JSON字符串
        $request->setBody(json_encode($body));

//      为请求添加ISV模式过滤器，自动根据算法计算开放平台鉴权及签名信息
        $request->addFilter($isvFilter);
//      为请求添加错误响应解析过滤器，如果不添加需要手动解析错误响应
        $request->addFilter($errorResponseFilter);

        $options = new Options();

        $options->setAlgorithm(Options::MD5_SALT);
        //$options->setAlgorithm(Options::HMAC_MD5);
        //$options->setAlgorithm(Options::HMAC_SHA1);
        //$options->setAlgorithm(Options::HMAC_SHA256);
        //$options->setAlgorithm(Options::HMAC_SHA512);

        $response = $client->execute($request, $options);
        return json_decode($response->getBody(),true);
    }

    /**
     * 返回内容检查，false报错提示
     * @param $res
     * @return mixed|void
     */
    protected static function returnBody($res){
        if($res['success']==false){
            api_return(500,empty($res['subMsg'])?$res['msg']:$res['subMsg'],$res);
        }else{
            return $res;
        }
    }

    /**
     * 前置检查
     * @return void
     */
    public static function CheckPreCreateOrder($senderName,$senderAddress,$receiverAddress){
        $body=[[
            'senderContact'=>[
                'name'=>$senderName,
                'fullAddress'=>$senderAddress
            ],
            'receiverContact'=>[
                'fullAddress'=>$receiverAddress
            ],
            'orderOrigin'=>2,
            'customerCode'=>CUSTOMER_CODE,
            'productCode'=>PRODUCT_CODE
        ]];
        $path='/ecap/v1/orders/precheck';
        $res=self::request($path,$body);
        return self::returnBody($res);
    }

    /**
     * 创建订单
     * @param $orderId 订单号
     * @param $senderName 发件人名称
     * @param $senderMobile 发件人电话
     * @param $senderAddress 发件人地址
     * @param $receiverAddress 收件人地址
     * @param $receiverMobile 收件人电话
     * @param $weight 重量
     * @param $pickupStartTime 上门取货开始时间
     * @param $pickupEndTime 上门取货结束时间
     * @return mixed|void
     * @throws \Lop\LopOpensdkPhp\SdkException
     */
    public static function CreateOrder($orderId,$senderName,$senderMobile,$senderAddress,$receiverAddress,$receiverMobile,$weight,$pickupStartTime,$pickupEndTime){
        $body=[[
            'orderId'=>$orderId,
            'senderContact'=>[
                'name'=>$senderName,
                'mobile'=>$senderMobile,
                'fullAddress'=>$senderAddress,
            ],
            'receiverContact'=>[
                'name'=>$receiverAddress,
                'mobile'=>$receiverMobile,
                'fullAddress'=>$receiverAddress,
            ],
            'orderOrigin'=>2,
            'customerCode'=>CUSTOMER_CODE,
            'productsReq'=>[
                'productCode'=>PRODUCT_CODE
            ],
            'settleType'=>5,
            'cargoes'=>[
                [
                    'name'=>'旧衣物',
                    'quantity'=>1,
                    'weight'=>$weight,
                    'volume'=>100,
                    ''
                ]
            ],
            'goods'=>[
                [
                    'name'=>'旧衣物',
                    'quantity'=>1,
                ]
            ],
            'c2bAddedSettleTypeInfo'=>[
                'basicFreigthSettleType'=>3,
                'packageServiceSettleType'=>3,
                'guaranteeMoneyServiceSettleType'=>3,
                ''
            ],
            'extendProps'=>[
                'autoSubscribe'=>1
            ],
            'pickupStartTime'=>$pickupStartTime,
            'pickupEndTime'=>$pickupEndTime
        ]];
        $path='/ecap/v1/orders/create';
        $res=self::request($path,$body);
        return self::returnBody($res);
    }

    /**
     * 取消订单
     * @return void
     */
    public static function CancelOrder($waybillCode,$orderCode){
        $body=[[
            'waybillCode'=>$waybillCode,
            'orderCode'=>$orderCode,
            'orderOrigin'=>2,
            'cancelReason'=>'用户发起取消',
            'cancelReasonCode'=>1,
            'customerCode'=>CUSTOMER_CODE
        ]];
        $path='/ecap/v1/orders/cancel';
        $res=self::request($path,$body);
        return self::returnBody($res);
    }

    /**
     * 运单完成时信息查询
     * @param $orderId
     * @return mixed|void
     * @throws \Lop\LopOpensdkPhp\SdkException
     */
    public static function GetActualFeeInfo($waybillCode){
        $body=[[
            'waybillCode'=>$waybillCode,
            'orderOrigin'=>2,
            'customerCode'=>CUSTOMER_CODE,
        ]];
        $path='/ecap/v1/orders/actualfee/query';
        $res=self::request($path,$body);
        return self::returnBody($res);
    }

}
